package com.prizedraw.prize_draw.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Date;

@Data
@Component
@ConfigurationProperties(prefix = "prize-draw.jwt")
public class JwtUtil {
    private long expire;
    private String secret;
    private String header;

    /**
     * 生成JWT
     * @param userId
     * @return
     */
    public String generateToken(String userId){
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * expire);
        return Jwts.builder()
                .setHeaderParam("typ","JWT")
                .setSubject(userId)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate) //7天过期
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }

    /**
     * 解析JWT
     * @param jwt
     * @return
     */
    public Claims getClaimByToken(String jwt){
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt)
                    .getBody();
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 判断JWT是否过期
     * @param claims
     * @return
     */
    public boolean isTokenExpired(Claims claims){
        return claims.getExpiration().before(new Date());
    }
}
